<template>
  <div class="chatBotContainer">
    <div class="chatBotHeader">
      <div class="chatBotHeaderTitle">
        <div class="left">
          <img class="chatBotIcon" src="./assets/bot.png" />
          <div class="title">智能问诊助手</div>
        </div>
        <div class="right">
          <img @click="handelRefresh" class="refreshIcon" src="./assets/refresh.png" />
          <img @click="handleClose" class="closeIcon" src="./assets/close.png" />
        </div>
      </div>
      <div v-if="props.userInfo?.name" class="chatBotInfo">
        <div class="dot">
          <div class="innerDot"></div>
        </div>
        <div class="status">问诊中</div>
        <div class="text" style="font-weight: bold">{{ props.userInfo?.name }}</div>
        <div class="text" v-if="props.userInfo?.sex">{{ props.userInfo?.sex }}</div>
        <div class="text" v-if="props.userInfo?.age">{{ props.userInfo?.age }}岁</div>
      </div>
    </div>
    <img v-if="assistantState" class="assistant" src="./assets/assistant.png" />
    <div class="contentContainer" ref="contentContainer">
      <div v-for="(dialog, index) in dialogList">
        <UserDialog v-if="dialog.user" :content="dialog.user.content" :index="index"></UserDialog>
        <AiDialog
          v-if="dialog.ai"
          :content="dialog.ai.content"
          :status="dialog.ai.status"
          :index="index"
          :handleScrollBottom="handleScrollBottom"
        ></AiDialog>
      </div>
    </div>
    <slot name="footer">
      <!-- <div class="inputContainer">
        <input class="input" v-model="chatBotStore.userInput" @keyup.enter="handleSendMsg" />
      </div> -->
      <Recorder ref="footerContainer" :handleScrollBottom="handleScrollBottom" />
    </slot>

    <Tooltip v-model:visible="tooltipProps.visible" :location="tooltipProps.location">
      <div class="li" @click="handleCopy"><CopyOutlined /> 复制</div>
    </Tooltip>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive, watch } from 'vue'
import { CopyOutlined } from '@ant-design/icons-vue'
import { useChatBotStore } from './chat-bot-store'
import UserDialog from './components/user-dialog.vue'
import AiDialog from './components/ai-dialog.vue'
import Recorder from './components/Recorder.vue'
import Tooltip from './components/Tooltip.vue'
import { handleCopyToClipboard } from './util'
import { message } from 'ant-design-vue'

const props = defineProps({ userInfo: Object })

const chatBotStore = useChatBotStore()
const contentContainer = ref(null)
const footerContainer = ref(null)
const tooltipProps = reactive({
  visible: false,
  location: [],
  selectionText: ''
})

// 初始化是否展示助理的图片
const assistantState = computed(() => {
  return !chatBotStore.dialogList.length && !props.userInfo?.name
})
// 对话聊天的数据
const dialogList = computed(() => {
  return chatBotStore.dialogList.length ? chatBotStore.dialogList : chatBotStore.initDialogList
})

function handleSendMsg() {
  chatBotStore.getAIAnswer(null, handleScrollBottom)
}

const handleScrollBottom = () => {
  contentContainer.value.scrollTo({
    top: contentContainer.value.scrollHeight,
    behavior: 'smooth'
  })
}

const handelRefresh = () => {
  chatBotStore.dialogList = []
  footerContainer.value?.handleEmpty?.()
}

const handleClose = () => {
  // window.ipcRenderer.send('window-min') // 窗口最小化
  window.ipcRenderer.send('window-close') // 窗口退出
}

const handleCopy = () => {
  handleCopyToClipboard(tooltipProps.selectionText).then(
    () => {
      message.success('复制成功')
    },
    () => {
      message.success('复制失败')
    }
  )
  tooltipProps.visible = false
}

const handleSelection = (event) => {
  const selection = window.getSelection()
  const text = selection.toString()?.trim()

  // 防止文本框外的乱点击
  const contentTextDoms = contentContainer.value?.querySelectorAll('.contentText')
  const isChild = [...contentTextDoms]?.some?.((dom) => dom.contains(event.target))

  if (
    text &&
    isChild &&
    selection.rangeCount > 0 &&
    contentContainer.value.contains(selection.anchorNode)
  ) {
    // 防止与tooltip中的click事件触发时机冲突，加上一个定时器
    setTimeout(() => {
      tooltipProps.location = [event.pageX, event.pageY]
      tooltipProps.selectionText = text
      tooltipProps.visible = true
    }, 100)
  }
}

const stopUserInfoWatch = watch(
  () => props.userInfo,
  (count, prevCount) => {
    handelRefresh()
  }
)

onMounted(() => {
  contentContainer.value?.addEventListener?.('mouseup', handleSelection)
})
onUnmounted(() => {
  stopUserInfoWatch?.()
  contentContainer.value?.removeEventListener?.('mouseup', handleSelection)
})
</script>

<style lang="less" scoped>
.chatBotContainer {
  width: 100%;
  height: 100%;
  background-image: url('./assets/bg.png');
  background-size: cover;
  display: flex;
  flex-direction: column;
}

.inputContainer {
  display: flex;
  padding: 8px 16px;
  width: 100%;
  height: 62px;
  box-sizing: border-box;

  .input {
    width: 100%;
    border-radius: 8px;
    border: 1px solid #4f54ff;
  }
}

.chatBotHeader {
  width: 100%;
  margin-bottom: 16px;

  .chatBotHeaderTitle {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 56px;
    padding: 10px 20px 10px 16px;
    background-color: white;
    box-shadow: 0px 4px 8px 0px rgba(198, 171, 211, 0.15);

    .left {
      display: flex;
      align-items: center;
      flex-grow: 1;
      -webkit-app-region: drag;

      .chatBotIcon {
        height: 36px;
        width: 36px;
      }

      .title {
        margin-left: 12px;
        height: 22px;
        font-size: 14px;
        font-weight: 400;
        color: #040a14;
        line-height: 22px;
      }
    }

    .right {
      display: flex;
      align-items: center;

      .refreshIcon {
        width: 20px;
        height: 20px;
        margin-right: 20px;

        &:hover {
          cursor: pointer;
          content: url('./assets/refresh-hover.png');
        }
      }

      .closeIcon {
        width: 20px;
        height: 20px;

        &:hover {
          cursor: pointer;
          content: url('./assets/close-hover.png');
        }
      }
    }
  }

  .chatBotInfo {
    background: rgba(255, 255, 255, 0.8);
    width: 100%;
    height: 48px;
    display: flex;
    align-items: center;
    padding-left: 16px;
    box-sizing: border-box;

    .dot {
      position: relative;
      width: 12px;
      height: 12px;
      border-radius: 6px;
      background: rgba(88, 99, 255, 0.3);

      .innerDot {
        position: absolute;
        width: 8px;
        height: 8px;
        border-radius: 4px;
        background: #5863ff;
        top: 2px;
        left: 2px;
      }
    }

    .status {
      margin-left: 5px;
      width: 36px;
      height: 22px;
      font-size: 12px;
      font-weight: 400;
      color: #4e5969;
      line-height: 22px;
    }

    .text {
      margin-left: 12px;
      height: 22px;
      font-size: 14px;
      font-weight: 500;
      color: #040a14;
      line-height: 22px;
    }
  }

  .chatBotInfo {
    width: 100%;
    height: 40px;
  }
}

.assistant {
  width: 100%;
  height: 200px;
  object-fit: contain;
  margin-bottom: 16px;
}

.contentContainer {
  overflow-y: auto;
  /* 112：header 40：input */
  flex-grow: 1;

  /* 滚动条整体宽度 */
  &::-webkit-scrollbar {
    width: 8px;
  }

  /* 滚动条轨道背景色（通常较淡） */
  &::-webkit-scrollbar-track {
    background: #f5f5f5;
  }

  /* 滚动条滑块颜色 */
  &::-webkit-scrollbar-thumb {
    background: #999;
    border-radius: 4px;
  }

  /* 鼠标悬停时滑块颜色变化，增强交互感 */
  &::-webkit-scrollbar-thumb:hover {
    background: #777;
  }
}

.li {
  cursor: pointer;

  &:hover {
    color: #4096ff;
  }
}
</style>
